package com.suray.attendance.db.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.suray.attendance.common.utils.LoggerUtil;
import com.suray.attendance.db.mapper.UserInfoMapper;
import com.suray.attendance.db.service.DingDeptDBService;
import com.suray.attendance.db.service.DingUserDBService;
import com.suray.attendance.model.pojo.UserInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Author: jianglinyu
 * @CreateTime: 2023-07-08  14:06
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class DingUserDBServiceImpl implements DingUserDBService {

    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private DingDeptDBService dingDeptDBService;

    /**
     * @param userInfoList
     * @description: 批量新增或者修改用户的基本信息到mysql数据库  TODO：修改userInfo待完善
     * @author: jianglinyu
     * @date: 2023/7/11 11:25
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertOrUpdateToDB(List<UserInfo> userInfoList) {
        if(userInfoList!=null&& userInfoList.size()>0){
            try {
                userInfoMapper.batchInsert(userInfoList);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("批量新增或者修改用户的基本信息到mysql数据库失败");
            }
        }
    }

    @Override
    public UserInfo getUserInfoByName(String name) {
        if(StringUtils.isEmpty(name)){
            return null;
        }
        List<UserInfo> userInfoList = userInfoMapper.selectList(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getName, name));
        if (userInfoList==null || userInfoList.size()<1){
            return null;
        } else if(userInfoList.size()==1){
            // 人:部门=1：1
            return userInfoList.get(0);
        }
        // 人:部门=1：n 使用Java的流（Stream）来获取id列表
        List<Long> deptIdList = userInfoList.stream()
                .map(UserInfo::getDeptId)
                .collect(Collectors.toList());
        // 一个人有多个部门，此时查询部门的pid,且判断pid的deptInfo中的pid是否为1
        Long deptId = getDeptIdByRecursionWay(deptIdList);
        UserInfo userInfo = userInfoList.get(0);
        userInfo.setDeptId(deptId);
        return userInfo;
    }

    @Override
    public UserInfo getUserInfoById(String userId) {
        if(StringUtils.isEmpty(userId)){
            return null;
        }
        try {
            return userInfoMapper.selectList(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getId,userId)).get(0);
        } catch (Exception e) {
            LoggerUtil.error("根据userId="+userId+"在表user_info表中获取用户数据失败"+e.getMessage(),DingUserDBServiceImpl.class);
            throw new RuntimeException("根据userId="+userId+"在表user_info表中获取用户数据失败"+e.getMessage());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteAll() {
        try {
            Integer userInfoCount = userInfoMapper.selectCount(new LambdaQueryWrapper<>());
            int delete = userInfoMapper.delete(new LambdaQueryWrapper<>());
            if (delete!=userInfoCount){
                throw new RuntimeException("删除ding_user_info全表数据出现异常");
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtil.error("删除ding_user_info全表数据出现异常"+e.getMessage(),DingUserDBServiceImpl.class);
            throw new RuntimeException("删除ding_user_info全表数据出现异常");
        }
    }


    private Long getDeptIdByRecursionWay(List<Long> deptIdList) {
        List<Map<Long, Long>> deptIdMap = dingDeptDBService.getDeptIdListById(deptIdList);// pid,id
        Set<Long> deptPidSet = new HashSet<>();
        for (Map<Long, Long> longLongMap : deptIdMap) {
            Long pid = longLongMap.get("pid");
            if (pid==1L){
                return longLongMap.get("id");
            }
            deptPidSet.add(pid);
        }
        if(deptPidSet.size()==1){
            return deptPidSet.iterator().next();
         }else {
            return getDeptIdByRecursionWay(new ArrayList<Long>(deptPidSet));
        }
    }


}